import ctypes
from ctypes import *
from ctypes.wintypes import WORD
from ctypes.wintypes import DWORD
from ctypes.wintypes import BYTE
from ctypes.wintypes import POINTER
import os, sys, platform

dllobj = None

def InitializeWinIo(dlldir = None):
    global dllobj
    if dllobj:
        return True
    
    if not dlldir:
        ddir = os.path.dirname(os.path.realpath(sys.argv[0]))
    else:
        ddir = dlldir
        
    bitsize, sysname = platform.architecture()
    if bitsize == '32bit':
        dp = os.path.join(ddir, 'WinIo32.dll')
    elif bitsize == '64bit':
        dp = os.path.join(ddir, 'WinIo64.dll')
    dllobj = ctypes.WinDLL(dp)
    
    func = dllobj.InitializeWinIo
    func.restype = c_bool
    return func()

def ShutdownWinIo():
    global dllobj
    if not dllobj:
        return False
    dllobj.ShutdownWinIo()
    del dllobj
    return True
    
def GetPortVal(portAddr, bytesSize = 1):
    global dllobj
    func = dllobj.GetPortVal
    func.argtypes =[WORD, POINTER(DWORD), BYTE]  
    func.restype = c_bool
    
    ret = DWORD()
    res = func(portAddr, ret, bytesSize)
    return ret.value, res
        
def SetPortVal(portAddr, portVals, bytesSize = 1):
    global dllobj
    func = dllobj.SetPortVal
    func.argtypes = [WORD, DWORD, BYTE]
    func.restype = c_bool
    
    return func(portAddr, portVals, bytesSize)
    
if __name__ == '__main__':
    print InitializeWinIo()
    #ret = GetPortVal(0xc800, 2)
    ret = SetPortVal(0xc800 & ~(0x0001 << 2), 0, 2)
    print ret
    ShutdownWinIo()
